package com.hudson.core.json;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.hudson.common.domain.InnerMessage;
import com.hudson.common.domain.meta.BrokerInfo;
import com.hudson.common.domain.meta.TopicQueueMap;
import com.hudson.common.domain.request.DefaultSendMessageReq;
import com.hudson.common.domain.request.PushMessageReq;
import com.hudson.common.domain.request.SendRelayMessageReq;
import com.hudson.common.domain.response.DefaultSendMessageResp;
import com.hudson.common.domain.response.PushMessageResp;
import com.hudson.common.enums.MessageTypeEnum;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 * @Author: 渔小鲤
 * @DateTime: 2025/7/19 2:41
 **/
public class MessageTypeAdapter extends TypeAdapter<InnerMessage<?>> {

    private final Gson gson = new Gson();


    @Override
    public void write(JsonWriter jsonWriter, InnerMessage<?> message) throws IOException {
        JsonObject obj = new JsonObject();
        // 处理空类型情况
        if (message.getType() == null) {
            obj.addProperty("type", "");
        } else {
            obj.addProperty("type", message.getType());
        }

        // 正确地将消息内容转换为JsonElement
        JsonElement messageElement = gson.toJsonTree(message.getMessage());

        obj.add("message", messageElement);
        gson.toJson(obj, jsonWriter);
    }

    @Override
    public InnerMessage<?> read(JsonReader in) throws IOException {
        JsonElement jsonElement = gson.getAdapter(JsonElement.class).read(in);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String type = jsonObject.get("type").getAsString();
        // 检查是否存在message字段，如果不存在则设置为null
        JsonElement messageElement = jsonObject.has("message") ? jsonObject.get("message") : null;

        MessageTypeEnum msgType = MessageTypeEnum.fromType(type);

        Class<?> targetClass = switch (msgType) {
            case SEND_MESSAGE_REQ -> DefaultSendMessageReq.class;
            case SEND_RELAY_MESSAGE_REQ -> SendRelayMessageReq.class;
            case PUSH_MESSAGE_REQ -> PushMessageReq.class;
            case PUSH_MESSAGE_RESP -> PushMessageResp.class;
            case QUEUE_MAP -> TopicQueueMap.class;
            case GET_BROKER_INFO -> Map.class;
            case BROKER_INFO_MESSAGE -> BrokerInfo.class;
            case SUCCESS_MESSAGE,IDLE_MESSAGE -> Object.class;
            case SEND_MESSAGE_RESP -> DefaultSendMessageResp.class;
            case ADD_TOPIC_QUEUE -> List.class;
            default -> throw new IllegalArgumentException("Unsupported message type: " + type);
        };

        // 添加对messageElement为null的检查
        if (messageElement == null) {
            // 如果messageElement为null，直接返回null消息
            return new InnerMessage<>(type, null);
        }

        if (messageElement.isJsonArray()) {
            // 处理 List 类型
            Type listType = TypeToken.getParameterized(List.class, targetClass).getType();
            // 特殊处理ADD_TOPIC_QUEUE类型，指定泛型参数为String
            if (msgType == MessageTypeEnum.ADD_TOPIC_QUEUE) {
                listType = new TypeToken<List<String>>(){}.getType();
            } else {
                listType = TypeToken.getParameterized(List.class, targetClass).getType();
            }
            List<?> list = gson.fromJson(messageElement, listType);
            return new InnerMessage<>(type, list);
        } else {
            // 处理单个对象
            Object message = gson.fromJson(messageElement, targetClass);
            return new InnerMessage<>(type, message);
        }
    }
}
